<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\AdminActionTypeEnum;
use App\Enums\CheckStatusEnum;
use App\Exceptions\ApiException;
use App\Format\ProposalFormat;
use App\Models\Proposal;
use App\Models\User;
use App\Models\UserProfile;

class ProposalService
{
    public function createProposal(ProposalFormat $proposalFormat)
    {
        if (empty($proposalFormat->getImages())) {
            $proposalFormat->setImages('');
        }
        $profile = UserProfile::query()
            ->where('user_id', $proposalFormat->getUserId())
            ->select('check_status')->first();

        if (empty($profile)) {
            throw new ApiException('请先完善个人信息', 1);
        }

        if ($profile->check_status != CheckStatusEnum::CHECK_ADOPT) {
            throw new ApiException('个人信息尚在审核中', 1);
        }

        $proposalFormat->setPushTime(time());
        Proposal::query()->create($proposalFormat->toArrayNotNull());
        return true;
    }

    public function reProposal(int $proposalId, int $answerUserId, string $reMessage)
    {
        /** @var null|Proposal $proposal */
        $proposal = Proposal::query()->find($proposalId);
        if (! $proposal) {
            throw new ApiException('建议不存在', 1);
        }
        $proposal->answer_user_id = $answerUserId;
        $proposal->re_message = $reMessage;
        $proposal->save();
        return true;
    }

    public function getUserProposals(int $page, int $pageSize, $userId, array $search)
    {
        $builder = Proposal::query()->where('user_id', $userId);
        if (isset($search['title'])) {
            $builder->where('title', 'like', '%' . $search['title'] . '%');
        }
        if (isset($search['start_date'], $search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['start_date']) && ! isset($search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
        }
        if (! isset($search['start_date']) && isset($search['end_date'])) {
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['order_column'], $search['order_type'])) {
            $builder->orderBy($search['order_column'], $search['order_type']);
        }
        $count = $builder->count();
        $list = $builder->skip(($page - 1) * $pageSize)
            ->take($pageSize)
            ->orderByDesc('id')
            ->get();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function getUserProposalDetail(int $id, int $userId)
    {
        /** @var null|Proposal $proposal */
        $proposal = Proposal::query()->find($id);
        if (! $proposal) {
            throw new ApiException('建议不存在', 1);
        }
        if ($proposal->user_id != $userId) {
            throw new ApiException('不能查看非自己的建议', 1);
        }
        $res = $proposal->toArray();
        $res['publish_user_name'] = User::query()->select('name')->find($userId)->name;
        return $res;
    }

    public function adminGetProposalDetails(int $id)
    {
        $proposal = Proposal::query()->with('user')->find($id);
        if (! $proposal) {
            throw new ApiException('建议不存在', 1);
        }
        return $proposal;
    }

    public function setScore(int $id, int $score, string $remarks)
    {
        /** @var null|Proposal $proposal */
        $proposal = Proposal::query()->find($id);
        if (empty($proposal)) {
            throw new ApiException('意见不存在', 1);
        }
        if ($proposal->answer_user_id == 0) {
            throw new ApiException('未回复不能打分', 1);
        }
        $proposal->score = $score;
        if (! empty($remarks)) {
            $proposal->remarks = $remarks;
        }
        $proposal->save();
        return true;
    }

    public function getLists(int $page, int $pageSize, array $search)
    {
        $builder = Proposal::query();

        if (isset($search['title'])) {
            $builder->where('title', 'like', '%' . $search['title'] . '%');
        }
        if (isset($search['reply']) && $search['reply'] == 1) {
            $builder->where('answer_user_id', '>', 0);
        }
        if (isset($search['reply']) && $search['reply'] == 2) {
            $builder->where('answer_user_id', 0);
        }
        $count = $builder->count();
        $list = $builder
            ->with('user')
            ->skip(($page - 1) * $pageSize)
            ->take($pageSize)->get();
        if (! empty($search)) {
            adminLog(new Proposal(), AdminActionTypeEnum::SELECT, '查询未诉先办');
        }
        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function reMessage(int $id, int $answerUserId, string $re_images, string $reMessage)
    {
        /** @var null|Proposal $proposal */
        $proposal = Proposal::query()->find($id);
        if (empty($proposal)) {
            throw new ApiException('数据不存在', 1);
        }
        $proposal->answer_user_id = $answerUserId;
        $proposal->re_message = $reMessage;
        $proposal->re_images = $re_images;
        $proposal->save();
        return true;
    }

    public function delete(int $id)
    {
        $proposal = Proposal::query()->find($id);
        if (empty($proposal)) {
            throw new ApiException('数据不存在', 1);
        }
        $proposal->delete();

        return true;
    }
}
